<?php
/**
 * XML detail report
 *
 * This class formats an incoming XML string and outputs
 * a XML Detail Report with Base64 encoded images.
 * @package Reports
 */

/**
 *
 */
require_once(AD_SERVER_PATH . '/pkgs/server.php');
require_once(AD_SERVER_PATH . '/reports/xml_report.php');

/**
 * XML detail report
 *
 * This class formats an incoming XML string and outputs
 * a XML Detail Report with Base64 encoded images.
 * @package Reporting
 */
class CXML_detail extends CXML_report
{
	/**
	 * Outputs detailed XML report
	 *
	 * Takes XML results and forms it into detail XML report.
	 */
	public function get_report()
	{
		header ('content-type: text/xml');

		$data  = '<?xml version="1.0"?>';
		$data .= PHP_EOL;
		$data .= $this->_pack_xml();
		echo $data;
	}

	/**
	 * Pack XML
	 *
	 * Packs all listing data, including images, into XML
	 * @return string $xml
	 */
	private function _pack_xml()
	{
		$xml_data = simplexml_load_string($this->get_data());

		$xml = '<listings>';

		foreach ($xml_data->rows->row AS $row)
		{
			$xml .= '<listing>';
			$xml .= CUtils::pack_xml($row, 'data');
			$xml .= $this->_pack_imgs($row->ml_number);
			$xml .= '</listing>';
		}
		$xml .= '</listings>';

		return $xml;
	}

	/**
	 * Base64 encode images and pack them into XML
	 *
	 * This is needed so that binary image can be stored in XML.
	 * @param int $ml_number
	 * @return string $output
	 */
	private function _pack_imgs($ml_number)
	{
		$server_obj = new CServer();

		$images = $server_obj->get_img($ml_number);

		if (is_array($images))
		{
			$output = '<imgs>';
			foreach ($images AS $image)
			{
				$output .= '<img>' . htmlspecialchars(base64_encode($image['Data'])) . '</img>';
			}
			$output .= '</imgs>';
			return $output;
		}
		return null;
	}
}
